package algorithm1_v2;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.lang.management.ManagementFactory;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Task1 implements Callable<Object>{

	private static void writeLeader() {
		SystemInfo info = SystemInfo.INSTANCE;
		BufferedWriter fileLeader;
		try {
			fileLeader = new BufferedWriter(new FileWriter("leader"));
			fileLeader.write(info.leader.toString());
			fileLeader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static void sendMessage(){
		SystemInfo info = SystemInfo.INSTANCE;
		try {
		Socket socket = new Socket("localhost", 12345);
		
			ObjectOutputStream clientInputStream = new ObjectOutputStream(
					socket.getOutputStream());
			Message message= new Message(new StringBuilder(info.leader),new StringBuilder(ManagementFactory.getRuntimeMXBean().getName()),info.recovered);
			clientInputStream.writeObject(message);
			clientInputStream.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	@Override
	public Object call() throws Exception {
		//Thread.sleep(info.incarnation[0]+info.timeUnit[0]); //Delay hau Iniciationen sartu da scheduler exekutatzerakoan
		writeLeader();
		ScheduledExecutorService executor = (ScheduledExecutorService) Executors.newSingleThreadExecutor();
		SystemInfo info = SystemInfo.INSTANCE;
		executor.scheduleAtFixedRate(new Runnable() {
			public void run() {
				sendMessage();
			}
		}, 0, info.timeUnit[0], TimeUnit.MILLISECONDS);
		return null;
	}
	

}
